<template>
  <div class="hello">

    <button @click="handleSocketSent">socket-send</button>

    <input type="text" v-model="socketData">

    <div v-text="socketDataBack"></div>
    <div>
      <button @click="wsClose">关闭连接</button>
    </div>
  </div>
</template>

<script>
export default {
  name: 'HelloWorld',
  data () {
    return {
      msg: 'Welcome to Your Vue.js App',
      socketData:'',
      socketDataBack:'',
    }
  },
  methods:{
    //socket测试方法
    handleSocketSent(socketDataSent){
      console.log(socketDataSent);

      this.socketInit();

    },
    socketInit(){
      this.socket = new WebSocket('ws://192.168.0.105:8181/wschat/ws');

      //  websocket事件
      this.socket.onopen = this.onSocketOpen;
      this.socket.onclose = this.onSocketClose;
      this.socket.onerror = this.onSocketError;
      this.socket.onmessage = this.onSocketMessage;
    },

    onSocketOpen(){
      console.log('socketOpen',this.socketData);
      console.log('数据发送中...',this.socketData);
      this.socketSent(this.socketData);
    },
    onSocketError(err){
      console.log('连接发生错误...');
      console.log('err...',err);
    },
    onSocketClose(){
      console.log('连接关闭...');
    },
    onSocketMessage(data_get){
      this.socketDataBack = data_get.data;
      console.log('数据接收中...',data_get);
    },
    socketSent(message){
      //序列化
      message = JSON.stringify(message);
      this.socket.send(message);
      console.log('socketSent数据发送完成');
    },

    wsClose(){
      this.socket.close();
      console.log('关闭websocket')
    },
    //socket测试方法
  }
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
h1, h2 {
  font-weight: normal;
}
ul {
  list-style-type: none;
  padding: 0;
}
li {
  display: inline-block;
  margin: 0 10px;
}
a {
  color: #42b983;
}
</style>
